package com.yangtzeu.jwc.fragment;

import android.annotation.SuppressLint;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.yangtzeu.jwc.activity.LoginActivity;
import com.yangtzeu.jwc.activity.MainActivity;
import com.yangtzeu.jwc.activity.UserActivity;
import com.yangtzeu.jwc.app.MyApplication;
import com.yangtzeu.jwc.businessservice.BusinessHttpCallBack;
import com.yangtzeu.jwc.businessservice.impl.LoaderBusiness;
import com.yangtzeu.jwc.businessservice.impl.StudentServiceImpl;
import com.yangtzeu.jwc.customview.CircleImageView;
import com.yangtzeu.jwc.customview.CustomeProgressDialog;
import com.yangtzeu.jwc.domain.Student;
import com.yangtzeu.jwc.utils.AllActivitys;
import com.yangtzeu.jwc.utils.G;
import com.zhangdi.jwc.R;
import com.zjsx.lib.utils.L;

@SuppressLint("ValidFragment")
public class LeftFragment extends Fragment implements OnClickListener {
    private View mainView;
    private CircleImageView mainLeftUserHead;
    private TextView mainLeftUserName;
    private TextView mainLeftUserHeadLine;
    private RadioButton home, score, timetable, more;
    private MyApplication app = MyApplication.getInstance();
    private OnCheckedChangeListener changeListener;
    private ProgressDialog dialog;
    private Handler myHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            super.handleMessage(msg);
            switch (msg.what) {
                case G.SHOWPROGRESSDIALOG:
                    dialog = CustomeProgressDialog.show(getActivity(), "正在登录");
                    break;
                case G.DISMISSPROGRESSBAR:
                    if (dialog != null) {
                        dialog.dismiss();
                    }
                    break;
            }
        }

    };

    @SuppressLint("ValidFragment")
    public LeftFragment(OnCheckedChangeListener changeListener) {
        this.changeListener = changeListener;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mainView = inflater.inflate(R.layout.fragment_main_left, container, false);
        // CryptoUtils.testCrypto(getActivity());
        return mainView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onActivityCreated(savedInstanceState);
        initView();
        registerBoradcastReceiver();
        autoLogin(false);
    }

    public void initView() {
        RadioGroup radioGroup = (RadioGroup) getActivity().findViewById(R.id.radiogroup_left);
        home = (RadioButton) getActivity().findViewById(R.id.home);
        score = (RadioButton) getActivity().findViewById(R.id.score);
        timetable = (RadioButton) getActivity().findViewById(R.id.timetable);
        more = (RadioButton) getActivity().findViewById(R.id.more);
        home.setOnCheckedChangeListener(changeListener);
        score.setOnCheckedChangeListener(changeListener);
        timetable.setOnCheckedChangeListener(changeListener);
        more.setOnCheckedChangeListener(changeListener);

        mainLeftUserName = (TextView) getActivity().findViewById(R.id.main_left_username);
        mainLeftUserHead = (CircleImageView) getActivity().findViewById(R.id.main_left_user_head);
        mainLeftUserHeadLine = (TextView) getActivity().findViewById(R.id.main_left_userheadline);
        mainLeftUserName.setText("登陆");

        mainLeftUserName.setOnClickListener(this);
        mainLeftUserHead.setOnClickListener(this);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unRegisterBroadcastReceiver();
    }

    public void setLogin() {
        if (MainActivity.student.getSphoto() != null) {
            LoaderBusiness.loadImage(MainActivity.student.getSphoto(), mainLeftUserHead);
        }
        mainLeftUserName.setText(MainActivity.student.getSname() + "|" + MainActivity.student.getSclass());
    }

    public void setUnLogin() {
        MainActivity.student = null;
        mainLeftUserHead.setImageResource(R.drawable.icon_student);
        mainLeftUserName.setText("登陆");
        Toast.makeText(getActivity(), "注销成功", Toast.LENGTH_SHORT).show();
    }

    public void registerBoradcastReceiver() {
        L.e("注册消息接收广播");
        IntentFilter myIntentFilter = new IntentFilter();
        myIntentFilter.addAction(G.BROADCAST_LOGIN);
        myIntentFilter.addAction(G.BROADCAST_LOGOUT);
        getActivity().registerReceiver(loginReceiver, myIntentFilter);
    }

    public void unRegisterBroadcastReceiver() {
        L.e("解除消息接收广播");
        getActivity().unregisterReceiver(loginReceiver);
    }

    public BroadcastReceiver loginReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO Auto-generated method stub
            if (G.BROADCAST_LOGIN.equals(intent.getAction())) {
                setLogin();
            } else if (G.BROADCAST_LOGOUT.equals(intent.getAction())) {
                setUnLogin();
            }
        }

    };

    private void showLoginWindow() {
        Intent intent = new Intent();
        intent.setClass(getActivity(), LoginActivity.class);
        startActivity(intent);
    }

    private void autoLogin(boolean showWindow) {
        Student savedStudent = StudentServiceImpl.getInstance().getSavedStudent(getActivity());
        if (MainActivity.student != null)
            return;
        if (savedStudent == null) {
            if (showWindow) {
                showLoginWindow();
            }
            return;
        }
        myHandler.sendEmptyMessage(G.SHOWPROGRESSDIALOG);
        StudentServiceImpl.getInstance().login(savedStudent.getSno(), savedStudent.getSpassword(), "1", new BusinessHttpCallBack() {
            @Override
            public void onFailure(byte[] responseBody, String failuremsg, boolean isNoticeDialog) {
                myHandler.sendEmptyMessage(G.DISMISSPROGRESSBAR);
            }

            @Override
            public void onSuccess(byte[] responseBody, String successMsg, boolean isNoticeDialog, Object obj) {
                L.e(successMsg);
                myHandler.sendEmptyMessage(G.DISMISSPROGRESSBAR);
            }

        });
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
            case R.id.main_left_username:
                autoLogin(true);
                break;
            case R.id.main_left_user_head:
                if (MainActivity.student != null) {
                    Intent itt = new Intent();
                    itt.setClass(getActivity(), UserActivity.class);
                    startActivity(itt);
                } else {
                    autoLogin(true);
                }
                break;
            default:
                break;
        }
    }

}
